package com.dw.dwdzcommerce.tools.commons.http;

import java.io.File;
import java.util.List;

import com.dw.dwdzcommerce.base.net.NameValuePair;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;

/**
 * Created by 周稹 on 15/10/31.
 * onResponse回调的参数是response，一般情况下，比如我们希望获得返回的字符串，可以通过response.body().string()获取；如果希望获得返回的二进制字节数组，则调用response.body().bytes()；如果你想拿到返回的inputStream，则调用response.body().byteStream()
 */
public class HttpUtilOKHttp implements IHttpUtil {
    private static OkHttpClient httpClient;
//    private static CallQueue queue = CallQueue.getQueue();

    public static OkHttpClient getClient() {
        if (httpClient == null) {
            synchronized (HttpUtilOKHttp.class) {
                if (httpClient == null) {
                    httpClient = new OkHttpClient();
                }
            }
        }
        return httpClient;
    }

//    /**
//     * 释放引用
//     *
//     * @param call
//     */
//    private static void releaseCall(Call call) {
//        queue.releaseCall(call.toString());
//    }
//
//    /**
//     * 结束并释放引用
//     */
//    public synchronized static void cancelAllCall() {
//        queue.endAllCall();
//    }

    /**
     * GET方法请求网络
     *
     * @param url
     * @param callback
     */
    @Override
    public void get(String url, Callback callback) {
        OkHttpClient httpClient = getClient();
        Request req = new Request.Builder().url(url).build();
        Call call = httpClient.newCall(req);
        call.enqueue(callback);
//        queue.entQueue(call);
    }

    /**
     * post方法请求网络
     *
     * @param url
     * @param vales
     * @param callback
     */
    @Override
    public void post(String url, List<NameValuePair> vales, Callback callback) {
        OkHttpClient httpClient = getClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        buildFormBuilder(builder, vales);
        Request req = new Request.Builder().url(url).post(builder.build()).build();

        Call call = httpClient.newCall(req);
        call.enqueue(callback);
    }

    /**
     * 上传文件
     *
     * @param url
     * @param files
     * @param fileKeys
     * @param pairs
     * @param callback
     */
    @Override
    public void uploadFiles(String url, File[] files, String[] fileKeys, List<NameValuePair> pairs, Callback callback) {
        if (!checkFileKeySizeValid(files, fileKeys)) {
            throw new RuntimeException("上传的文件与文件关键字数目不匹配");
        }
        OkHttpClient client = getClient();
        //构建键值对
        FormEncodingBuilder formBuilder = new FormEncodingBuilder();
        buildFormBuilder(formBuilder, pairs);
        //构建上传的文件，并将键值作为参数
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        buildMultipartBuilder(files, fileKeys, multipartBuilder, formBuilder);
        Request req = new Request.Builder().url(url).post(multipartBuilder.build()).build();
        Call call = client.newCall(req);
        call.enqueue(callback);
//        queue.entQueue(call);
    }

    private void buildMultipartBuilder(File[] files, String[] fileKeys, MultipartBuilder multipartBuilder, FormEncodingBuilder formBuilder) {
        for (int i = 0; i < files.length; i++) {
            multipartBuilder.addFormDataPart(fileKeys[i], files[i].getAbsolutePath());
        }
        multipartBuilder.addPart(formBuilder.build());
    }


    private void buildFormBuilder(FormEncodingBuilder builder, List<NameValuePair> vales) {
        for (NameValuePair pair : vales) {
            builder.add(pair.getName(), pair.getValue());
        }
    }

    private boolean checkFileKeySizeValid(File[] files, String[] fileKeys) {
        return files.length == fileKeys.length;
    }


}
